/*
 * @(#)DmsArchive.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.dms.bean.DmsArchive;
import com.dcivision.dms.web.ListDmsArchiveForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;

/**
  DmsArchiveDAObject.java

  This class is the data access bean for table "DMS_ARCHIVE".

  @author      Zoe Shum
  @company     DCIVision Limited
  @creation date   23/10/2003
  @version     $Revision: 1.16 $
*/

public class DmsArchiveDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.16 $";

  public static final String TABLE_NAME = "DMS_ARCHIVE";

  public DmsArchiveDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("ARCHIVE_NAME");
    this.vecDBColumn.add("ARCHIVE_TYPE");
    this.vecDBColumn.add("DESCRIPTION");
    this.vecDBColumn.add("ROOT_ID");
    this.vecDBColumn.add("ARCHIVE_DATE_FROM");
    this.vecDBColumn.add("ARCHIVE_DATE_TO");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.ARCHIVE_NAME, A.ARCHIVE_TYPE, A.DESCRIPTION, A.ROOT_ID, A.ARCHIVE_DATE_FROM, A.ARCHIVE_DATE_TO, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_ARCHIVE A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          DmsArchive tmpDmsArchive = new DmsArchive();
          tmpDmsArchive.setID(getResultSetInteger(rs, "ID"));
          tmpDmsArchive.setArchiveName(getResultSetString(rs, "ARCHIVE_NAME"));
          tmpDmsArchive.setArchiveType(getResultSetString(rs, "ARCHIVE_TYPE"));
          tmpDmsArchive.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsArchive.setRootID(getResultSetInteger(rs, "ROOT_ID"));
          tmpDmsArchive.setArchiveDateFrom(getResultSetTimestamp(rs, "ARCHIVE_DATE_FROM"));
          tmpDmsArchive.setArchiveDateTo(getResultSetTimestamp(rs, "ARCHIVE_DATE_TO"));
          tmpDmsArchive.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsArchive.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsArchive.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsArchive.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsArchive.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsArchive.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
          tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
          return(tmpDmsArchive);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());
    ListDmsArchiveForm listForm = (ListDmsArchiveForm) searchForm;

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.ARCHIVE_NAME, A.ARCHIVE_TYPE, A.DESCRIPTION, A.ROOT_ID, A.ARCHIVE_DATE_FROM, A.ARCHIVE_DATE_TO, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_ARCHIVE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        
        log.debug("date from : "+listForm.getAccessDateFrom() + "-=-=-=-=-=-=-");
        log.debug("date to : "+listForm.getAccessDateTo() + "-=-=-=-=-=-=-");
        /*
         * Update Code Start
         * Author			Jim.Zhou
         * Date				2006/04/11
         * Bug				#5070
         */
        if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
        	  // Use the "to_date" string representation.
          if (!Utility.isEmpty(listForm.getAccessDateFrom()) ) {
            sqlStat.append("AND A.CREATE_DATE >= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') ");//EIP-1408 07/01/08 LEE
            //sqlStat.append("AND A.ARCHIVE_DATE_FROM >= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') ");
          }
          if (!Utility.isEmpty(listForm.getAccessDateTo()) ) {
            sqlStat.append("AND A.CREATE_DATE <= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') ");//EIP-1408 07/01/08 LEE
            //sqlStat.append("AND A.ARCHIVE_DATE_TO <= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') ");
          }
        } else {
        	  // Use the normal apprach.
          if (!Utility.isEmpty(listForm.getAccessDateFrom()) ) {
            sqlStat.append("AND A.CREATE_DATE >= ? ");//EIP-1408 07/01/08 LEE
            //sqlStat.append("AND A.ARCHIVE_DATE_FROM >= ? ");
          }
          if (!Utility.isEmpty(listForm.getAccessDateTo()) ) {
            sqlStat.append("AND A.CREATE_DATE <= ? ");//EIP-1408 07/01/08 LEE
            //sqlStat.append("AND A.ARCHIVE_DATE_TO <= ? ");
          }
        }
        /*
         * Update Code End
         */
        
        

        // Form the WHERE clause for filtering.
        /*
        if (searchForm.isSearchable()) {
          String searchField = searchForm.getBasicSearchField();
          if (searchField.indexOf(".") < 0) {
            searchField = "A." + searchField;
          }
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }*/
       if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }
        
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());
        
        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }
        
        log.debug("SQL STATEMENT: "+sqlStat.toString());

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int i=1;
        this.setPrepareStatement(preStatCnt, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (!Utility.isEmpty(listForm.getAccessDateFrom()) ) {
         this.setPrepareStatement(preStatCnt, i++, listForm.getAccessDateFrom());
        }
        if (!Utility.isEmpty(listForm.getAccessDateTo()) ) {
          this.setPrepareStatement(preStatCnt, i++, listForm.getAccessDateTo().substring(0,listForm.getAccessDateTo().length()-8)+"23:59:59");
        }
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, i++, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        i=1;
        this.setPrepareStatement(preStat, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (!Utility.isEmpty(listForm.getAccessDateFrom()) ) {
         this.setPrepareStatement(preStat, i++, listForm.getAccessDateFrom());
        }
        if (!Utility.isEmpty(listForm.getAccessDateTo()) ) {
          this.setPrepareStatement(preStat, i++, listForm.getAccessDateTo().substring(0,listForm.getAccessDateTo().length()-8)+"23:59:59");
        }
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, i++, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          DmsArchive tmpDmsArchive = new DmsArchive();
          tmpDmsArchive.setID(getResultSetInteger(rs, "ID"));
          tmpDmsArchive.setArchiveName(getResultSetString(rs, "ARCHIVE_NAME"));
          tmpDmsArchive.setArchiveType(getResultSetString(rs, "ARCHIVE_TYPE"));
          tmpDmsArchive.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsArchive.setRootID(getResultSetInteger(rs, "ROOT_ID"));
          tmpDmsArchive.setArchiveDateFrom(getResultSetTimestamp(rs, "ARCHIVE_DATE_FROM"));
          tmpDmsArchive.setArchiveDateTo(getResultSetTimestamp(rs, "ARCHIVE_DATE_TO"));
          tmpDmsArchive.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsArchive.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsArchive.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsArchive.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsArchive.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsArchive.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
          tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
          tmpDmsArchive.setRecordCount(totalNumOfRecord);
          tmpDmsArchive.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpDmsArchive);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.ARCHIVE_NAME, A.ARCHIVE_TYPE, A.DESCRIPTION, A.ROOT_ID, A.ARCHIVE_DATE_FROM, A.ARCHIVE_DATE_TO, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_ARCHIVE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          DmsArchive tmpDmsArchive = new DmsArchive();
          tmpDmsArchive.setID(getResultSetInteger(rs, "ID"));
          tmpDmsArchive.setArchiveName(getResultSetString(rs, "ARCHIVE_NAME"));
          tmpDmsArchive.setArchiveType(getResultSetString(rs, "ARCHIVE_TYPE"));
          tmpDmsArchive.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsArchive.setRootID(getResultSetInteger(rs, "ROOT_ID"));
          tmpDmsArchive.setArchiveDateFrom(getResultSetTimestamp(rs, "ARCHIVE_DATE_FROM"));
          tmpDmsArchive.setArchiveDateTo(getResultSetTimestamp(rs, "ARCHIVE_DATE_TO"));
          tmpDmsArchive.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsArchive.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsArchive.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsArchive.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsArchive.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsArchive.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
          tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
          result.add(tmpDmsArchive);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsArchive tmpDmsArchive = (DmsArchive)((DmsArchive)obj).clone();
    Integer creatorID=sessionContainer.getUserRecordID();
    Integer updaterID=sessionContainer.getUserRecordID();
    if(!Utility.isEmpty(tmpDmsArchive.getCreatorID())){
      creatorID=tmpDmsArchive.getCreatorID();
    }
    if(!Utility.isEmpty(tmpDmsArchive.getUpdaterID())){
      updaterID=tmpDmsArchive.getUpdaterID();
    }
    
    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   DMS_ARCHIVE(ID, ARCHIVE_NAME, ARCHIVE_TYPE, DESCRIPTION, ROOT_ID, ARCHIVE_DATE_FROM, ARCHIVE_DATE_TO, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpDmsArchive.getArchiveName());
        setPrepareStatement(preStat, 3, tmpDmsArchive.getArchiveType());
        setPrepareStatement(preStat, 4, tmpDmsArchive.getDescription());
        setPrepareStatement(preStat, 5, tmpDmsArchive.getRootID());
        setPrepareStatement(preStat, 6, tmpDmsArchive.getArchiveDateFrom());
        setPrepareStatement(preStat, 7, tmpDmsArchive.getArchiveDateTo());
        setPrepareStatement(preStat, 8, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 9, new Integer(0));
        setPrepareStatement(preStat, 10, creatorID);
        setPrepareStatement(preStat, 11, currTime);
        setPrepareStatement(preStat, 12, updaterID);
        setPrepareStatement(preStat, 13, currTime);
        preStat.executeUpdate();
        tmpDmsArchive.setID(nextID);
        tmpDmsArchive.setCreatorID(creatorID);
        tmpDmsArchive.setCreateDate(currTime);
        tmpDmsArchive.setUpdaterID(updaterID);
        tmpDmsArchive.setUpdateDate(currTime);
        tmpDmsArchive.setUpdateCount(new Integer(0));
        tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
        tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
        return(tmpDmsArchive);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsArchive tmpDmsArchive = (DmsArchive)((DmsArchive)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE DMS_ARCHIVE ");
        sqlStat.append("SET  ARCHIVE_NAME=?, ARCHIVE_TYPE=?, DESCRIPTION=?, ROOT_ID=?, ARCHIVE_DATE_FROM=?, ARCHIVE_DATE_TO=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpDmsArchive.getArchiveName());
        setPrepareStatement(preStat, 2, tmpDmsArchive.getArchiveType());
        setPrepareStatement(preStat, 3, tmpDmsArchive.getDescription());
        setPrepareStatement(preStat, 4, tmpDmsArchive.getRootID());
        setPrepareStatement(preStat, 5, tmpDmsArchive.getArchiveDateFrom());
        setPrepareStatement(preStat, 6, tmpDmsArchive.getArchiveDateTo());
        setPrepareStatement(preStat, 7, new Integer(tmpDmsArchive.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        setPrepareStatement(preStat, 10, tmpDmsArchive.getID());
        setPrepareStatement(preStat, 11, tmpDmsArchive.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpDmsArchive.setUpdaterID(sessionContainer.getUserRecordID());
          tmpDmsArchive.setUpdateDate(currTime);
          tmpDmsArchive.setUpdateCount(new Integer(tmpDmsArchive.getUpdateCount().intValue() + 1));
          tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
          tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
          return(tmpDmsArchive);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    DmsArchive tmpDmsArchive = (DmsArchive)((DmsArchive)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   DMS_ARCHIVE ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpDmsArchive.getID());
        setPrepareStatement(preStat, 2, tmpDmsArchive.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpDmsArchive);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    DmsArchive tmpDmsArchive = (DmsArchive)this.oldValue;

    if (tmpDmsArchive != null) {
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getID()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveName()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveType()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getDescription()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getRootID()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveDateFrom()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveDateTo()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpDmsArchive.getUpdateDate()));
    }

    tmpDmsArchive = (DmsArchive)obj;
    if (tmpDmsArchive != null) {
      newValues.add(toAuditTrailValue(tmpDmsArchive.getID()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveName()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveType()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getDescription()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getRootID()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveDateFrom()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getArchiveDateTo()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpDmsArchive.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/


  
 /**
  * Gets the list of the archive record by the specified archive name
  * 
  * @param archiveName archive operation name
  * @return List of the DmsArchive object
  * @throws ApplicationException
  * 
  */
  public synchronized List getListByArchiveName(String archiveName) throws ApplicationException{
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.ARCHIVE_NAME, A.ARCHIVE_TYPE, A.DESCRIPTION, A.ROOT_ID, A.ARCHIVE_DATE_FROM, A.ARCHIVE_DATE_TO, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   DMS_ARCHIVE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.ARCHIVE_NAME= ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, archiveName);
        rs = preStat.executeQuery();
        while (rs.next()) {
          DmsArchive tmpDmsArchive = new DmsArchive();
          tmpDmsArchive.setID(getResultSetInteger(rs, "ID"));
          tmpDmsArchive.setArchiveName(getResultSetString(rs, "ARCHIVE_NAME"));
          tmpDmsArchive.setArchiveType(getResultSetString(rs, "ARCHIVE_TYPE"));
          tmpDmsArchive.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsArchive.setRootID(getResultSetInteger(rs, "ROOT_ID"));
          tmpDmsArchive.setArchiveDateFrom(getResultSetTimestamp(rs, "ARCHIVE_DATE_FROM"));
          tmpDmsArchive.setArchiveDateTo(getResultSetTimestamp(rs, "ARCHIVE_DATE_TO"));
          tmpDmsArchive.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsArchive.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsArchive.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsArchive.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsArchive.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsArchive.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsArchive.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsArchive.getCreatorID()));
          tmpDmsArchive.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsArchive.getUpdaterID()));
          result.add(tmpDmsArchive);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
  /**
   * Gets the archive name by the specified document ID.
   * 
   * @param docId document id
   * @return archive name, empty string if cannot find
   * @throws ApplicationException
   */
  public synchronized String getArchiveNameByDocID(Integer docId) throws ApplicationException {
      PreparedStatement preStat = null;
      ResultSet rs = null;
      StringBuffer sqlStat = new StringBuffer();
      String archiveName ="";

      synchronized(dbConn) {
        try {
          sqlStat.append("SELECT A.ARCHIVE_NAME ");
          sqlStat.append("FROM   DMS_ARCHIVE A, DMS_ARCHIVE_DETAIL B ");
          sqlStat.append("WHERE  A.ID = B.ARCHIVE_ID AND A.RECORD_STATUS = ? ");
          sqlStat.append("AND B.DOCUMENT_ID = ? ");
          preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
          
          this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
          this.setPrepareStatement(preStat, 2, docId);
          rs = preStat.executeQuery();
          if (rs.next()) {
            archiveName=getResultSetString(rs, "ARCHIVE_NAME"); 
          }
          return(archiveName); 
        } catch (ApplicationException appEx) {
          throw appEx;
        } catch (SQLException sqle) {
          log.error(sqle, sqle);
          throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
        } catch (Exception e) {
          log.error(e, e);
          throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
        } finally {
          try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
          try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        }
      }
    }
  
  
}
